package com.ywy.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ywy.common.rest.Result;
import com.ywy.entity.Post;
import com.ywy.entity.User;
import com.ywy.entity.UserMessage;
import com.ywy.service.PostService;
import com.ywy.service.UserMessageService;
import com.ywy.service.UserService;
import com.ywy.shiro.AccountProfile;
import com.ywy.utils.UploadUtil;
import com.ywy.vo.UserMessageVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ywy
 * @since 2021-12-24
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private PostService postService;
    @Autowired
    private UserMessageService userMessageService;
    @Autowired
    private UploadUtil uploadUtil;

    /**
     * 我的主页页面
     * @return
     */
    @GetMapping("/{id:\\d*}")
    public String detail(@PathVariable Integer id) {
        if (id == null) {
            id = getProfileId();
        }

        // 获取登录用户信息
        User user = userService.getById(id);
        user.setPassword(null);
        // 查询近30天的博客文章
        QueryWrapper<Post> queryWrapper = new QueryWrapper<Post>()
                .eq("user_id", id)
                .gt("create_time", DateUtil.offsetDay(new Date(), -30))
                .orderByDesc("create_time");
        List<Post> posts = postService.list(queryWrapper);

        req.setAttribute("user", user);
        req.setAttribute("posts", posts);

        return "/user/home";
    }

    /**
     * 用户主页
     * @return
     */
    @GetMapping("/home")
    public String home() {
        return "/user/" + getProfileId();
    }

    /**
     * 用户中心页面
     * @return
     */
    @GetMapping("/index")
    public String index() {
        return "/user/index";
    }

    /**
     * 基本设置页面
     * @return
     */
    @GetMapping("/set")
    public String set() {
        User user = userService.getById(getProfileId());
        user.setPassword(null);
        req.setAttribute("user", user);

        return "/user/set";
    }

    /**
     * 我的消息页面
     * @return
     */
    @GetMapping("/message")
    public String message() {
        // 查询我的消息
        QueryWrapper<UserMessage> queryWrapper = new QueryWrapper<UserMessage>()
                .eq("to_user_id", getProfileId())
                .orderByDesc("create_time");
        IPage<UserMessageVo> page = userMessageService.listByPage(getPage(), queryWrapper);

        // 把消息改成已读状态
        List<Integer> ids = new ArrayList<>();
        for(UserMessageVo messageVo : page.getRecords()) {
            if(messageVo.getStatus() == 0) {
                ids.add(messageVo.getId());
            }
        }
        // 批量修改消息为已读状态
        userMessageService.updateToRead(ids);

        req.setAttribute("pageData", page);
        return "/user/message";
    }

    /**
     * 用户发布的文章
     * @return
     */
    @ResponseBody
    @GetMapping("/publish")
    public Result publish() {
        QueryWrapper<Post> queryWrapper = new QueryWrapper<Post>()
                .eq("user_id", getProfileId())
                .orderByDesc("create_time");
        IPage page = postService.page(getPage(), queryWrapper);

        return Result.success(page);
    }

    /**
     * 用户收藏的文章
     * @return
     */
    @ResponseBody
    @GetMapping("/collection")
    public Result collection() {
        QueryWrapper<Post> queryWrapper = new QueryWrapper<Post>()
                .inSql("id", "SELECT post_id FROM user_collection where user_id = " + getProfileId());
        IPage page = postService.page(getPage(), queryWrapper);
        return Result.success(page);
    }

    /**
     * 修改基本设置
     * 修改用户信息、头像
     * @param user
     * @return
     */
    @ResponseBody
    @PostMapping("/set")
    public Result set(User user) {
        Integer userId = getProfileId();
        AccountProfile profile = getProfile();

        // 修改头像
        User tempUser = userService.getById(userId);
        if(StringUtils.isNotBlank(user.getAvatar())) {
            tempUser.setAvatar(user.getAvatar());
            userService.updateById(tempUser);
            // 更新登录用户的信息
            profile.setAvatar(user.getAvatar());
            SecurityUtils.getSubject().getSession().setAttribute("profile", profile);

            return Result.success("/user/set#avatar");
        }

        // 修改基本设置
        if (StringUtils.isBlank(user.getUsername())) {
            return Result.failure("昵称不能为空");
        }
        int count = userService.count(new QueryWrapper<User>()
                .eq("username", user.getUsername())
                .ne("id", userId));
        if(count > 0) {
            return Result.failure("该昵称已被占用");
        }

        tempUser.setUsername(user.getUsername());
        tempUser.setGender(user.getGender());
        tempUser.setSign(user.getSign());
        userService.updateById(tempUser);
        // 更新登录用户的信息
        profile.setUsername(user.getUsername());
        profile.setSign(user.getSign());
        SecurityUtils.getSubject().getSession().setAttribute("profile", profile);

        return Result.success("/user/set#info");
    }

    /**
     * 上传头像
     * @param file
     * @return
     */
    @ResponseBody
    @PostMapping("/upload")
    public Result uploadAvatar(@RequestParam("file") MultipartFile file) {
        return uploadUtil.upload(UploadUtil.TYPE_AVATAR, file);
    }

    /**
     * 修改密码
     * @param nowpass 当前密码
     * @param pass    新密码
     * @param repass  确认密码
     * @return
     */
    @ResponseBody
    @PostMapping("/repass")
    public Result repass(String nowpass, String pass, String repass) {
        // 判断两次密码是否一致
        if (!pass.equals(repass)) {
            return Result.failure("两次密码不一致");
        }

        // 查询用户信息
        User user = userService.getById(getProfileId());

        // 判断当前密码是否正确
        String nowPassMd5 = SecureUtil.md5(nowpass);
        if (!nowPassMd5.equals(user.getPassword())) {
            return Result.failure("密码不正确");
        }

        // 修改用户信息
        user.setPassword(SecureUtil.md5(pass));
        userService.updateById(user);

        return Result.success("/user/set#pass");
    }
}
